﻿/*
 *	Copyright (c) 2009 Queensland University of Technology. All rights reserved.
 *	The QUT Bioinformatics Collection is open source software released under the 
 *	Microsoft Public License (Ms-PL): http://www.microsoft.com/opensource/licenses.mspx.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using NCBI_Eutils.Eutils;
using QUT.Bio.SilverMap;
using QUT.Bio.Util;
using QUT.Bio.SilverMap.ObjectModel;

namespace BlastExplorer {
	/// <summary>
	/// Interaction logic for EntrezProteinPanel.xaml
	/// </summary>
	public partial class EntrezProteinPanel: UserControl {
		public bool IsOk {
			get;
			set;
		}

		public EntrezProteinPanel () {
			InitializeComponent();
		}

		IEnumerable<Xref> xrefs;
		StatusBar statusBar;
		Action whenItsOver;

		public void Initialise (
			IEnumerable<Xref> xrefs,
			StatusBar statusBar,
			Action whenItsOver
		) {
			this.xrefs = xrefs;
			this.statusBar = statusBar;
			this.whenItsOver = whenItsOver;
		}
		
		public void Run () {
			IEnumerable<string> giNumbers = from Xref xref in xrefs
											where xref.Database.Equals( "GI", StringComparison.InvariantCultureIgnoreCase )
											select xref.Id;

			if ( giNumbers.FirstOrDefault() != null ) {
				statusBar.WriteLine( "Communicating with NCBI..." );
				statusBar.StartProgress();
				EUtil eUtil = new EUtil();
				eUtil.EntrezQuery( EUtil.Database.protein, giNumbers, Success, Failure ); 
			}
		}

		private void Success ( Dictionary< string, GBSeqType> genbankRecords ) {
			foreach ( Xref xref in xrefs ) {
				if ( xref.Database.Equals( "GI" ) && genbankRecords.ContainsKey( xref.Id ) ) {
					grid.AddRow( new BasicGenbankDisplay( genbankRecords[xref.Id] ) );
				}
			}
			
			statusBar.Clear();
			IsOk = true;
			statusBar.StopProgress();
			
			if ( whenItsOver != null ) {
				whenItsOver();
			}
		}

		private void Failure () {
			statusBar.WriteLine( "Error communicating with NCBI" );
			IsOk = false;
			statusBar.StopProgress();
		}

		private void ScrollViewer_MouseLeftButtonDown ( object sender, MouseButtonEventArgs e ) {
			e.Handled = true;
		}

	}
}
